// src/Community.tsx
import React, { useState, useEffect } from 'react';
import {
  Row,
  Col,
  Tabs,
  Typography,
  Layout,
  Spin,
  message,
  Button
} from 'antd';
import {
  HeartOutlined,
  ReloadOutlined,
  ExclamationCircleOutlined,
  ClockCircleOutlined
} from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import Sidebar from './Sidebar';

const { Header, Content } = Layout;
const { Text } = Typography;

// 根据接口文档定义正确的 Recipe 类型
interface Recipe {
  id: number;
  title: string;
  duration: number;
  description: string;
  coverImage: string;
  difficulty: number;
  difficultyAvg: number;
  servings: number;
  likesCount: number;
  userId: number;
  createdAt: string;
  updatedAt: string;
  favoriteCount: number;
}

interface RecipeCommunityProps {
  onRecipeClick?: (recipeId: number) => void;
}

const RecipeCommunity: React.FC<RecipeCommunityProps> = ({ onRecipeClick }) => {
  const [activeTab, setActiveTab] = useState('发现');
  const [discoverRecipes, setDiscoverRecipes] = useState<Recipe[]>([]);
  const [followRecipes, setFollowRecipes] = useState<Recipe[]>([]);
  const [loading, setLoading] = useState(false);
  const [apiError, setApiError] = useState<string | null>(null);
  const navigate = useNavigate();

  // 颜色配置 - 与Message界面完全一致
  const colorConfig = {
    primary: '#e8d9c7', // 主色调 - 浅棕色
    primaryDark: '#8b4513', // 深棕色 - 文字颜色
    border: '#d4b896', // 边框色
    background: '#f8f4f0', // 背景色
    badge: '#a0522d', // 徽章颜色
    tabActive: '#e8d9c7', // 标签页激活颜色
  };

  // 获取当前用户ID
  const getUserId = (): number => {
    const userId = localStorage.getItem('userId');
    return userId ? parseInt(userId) : 7; // 默认使用7
  };

  // 构建 API 基础 URL - 使用代理（与Message界面一致）
  const getApiBaseUrl = (): string => {
    // 开发环境使用代理，生产环境使用直接地址
    if (import.meta.env.DEV) {
      return '/api'; // 使用 Vite 代理
    } else {
      return 'http://218.244.141.86:8080/api';
    }
  };

  // 获取认证token
  const getAuthToken = (): string => {
    const token = localStorage.getItem('token') || sessionStorage.getItem('token');
    if (token) {
      return `Bearer ${token}`;
    }
    // 如果没有token，使用默认token（从cURL中提取）
    return 'Bearer eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJyb290IiwiaWF0IjoxNzY0MDgzMjQ5LCJleHAiOjE3NjQxNjk2NDl9.t7nM__2KbwU-7SSDMOWSLsK7XNIJmEd6OlawxFlVlpA';
  };

  // API 调用函数 - 使用代理方案
  const fetchRecipes = async (endpoint: string) => {
    try {
      setLoading(true);
      setApiError(null);
      
      const userId = getUserId();
      const token = getAuthToken();
      
      const baseUrl = getApiBaseUrl();
      const url = `${baseUrl}${endpoint}`;
      
      console.log('正在请求:', url);
      console.log('用户ID:', userId);
      console.log('Token:', token.substring(0, 20) + '...');

      const response = await fetch(url, {
        method: 'GET',
        headers: {
          'Authorization': token,
          'Content-Type': 'application/json',
          'Accept': '*/*',
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
        },
        credentials: 'include' // 重要：包含凭据
      });
      
      console.log('响应状态:', response.status, response.statusText);

      if (!response.ok) {
        if (response.status === 403) {
          throw new Error('访问被拒绝 (403 Forbidden) - 认证失败');
        } else if (response.status === 404) {
          throw new Error('接口不存在 (404 Not Found)');
        } else {
          throw new Error(`HTTP错误! 状态码: ${response.status}`);
        }
      }
      
      // 首先检查响应内容类型
      const contentType = response.headers.get('content-type');
      console.log('响应Content-Type:', contentType);
      
      // 获取响应文本
      const responseText = await response.text();
      console.log('原始响应:', responseText);
      
      // 如果响应为空
      if (!responseText || responseText.trim() === '') {
        console.log('接口返回空响应，返回空数组');
        return [];
      }
      
      // 尝试解析 JSON
      try {
        const data = JSON.parse(responseText);
        console.log('解析后的数据:', data);
        
        // 确保数据是数组
        if (Array.isArray(data)) {
          return data.slice(0, 5); // 只取前5个
        } else {
          console.warn('接口返回的不是数组:', data);
          // 如果返回的是单个对象，包装成数组
          if (data && typeof data === 'object') {
            return [data];
          }
          return [];
        }
      } catch (jsonError) {
        console.error('JSON解析错误:', jsonError);
        console.error('原始响应文本:', responseText);
        throw new Error('数据格式错误');
      }
      
    } catch (error: any) {
      console.error('API调用失败:', error);
      const errorMessage = error.message || '网络请求失败';
      setApiError(errorMessage);
      message.error(`获取数据失败: ${errorMessage}`);
      return [];
    } finally {
      setLoading(false);
    }
  };

  // 加载发现界面食谱
  const loadDiscoverRecipes = async () => {
    const userId = getUserId();
    const recipes = await fetchRecipes(`/recommendations/discover/${userId}`);
    setDiscoverRecipes(recipes);
  };

  // 加载关注界面食谱
  const loadFollowRecipes = async () => {
    const userId = getUserId();
    const recipes = await fetchRecipes(`/userfollows/follower/${userId}/recipes`);
    setFollowRecipes(recipes);
  };

  // 重新加载数据
  const reloadData = () => {
    setApiError(null);
    switch (activeTab) {
      case '发现':
        loadDiscoverRecipes();
        break;
      case '关注':
        loadFollowRecipes();
        break;
    }
  };

  // 根据当前标签加载数据
  useEffect(() => {
    reloadData();
  }, [activeTab]);

  // 标签项配置 - 使用与Message界面相同的样式
  const tabItems = [
    { 
      key: '发现', 
      label: '发现'
    },
    { 
      key: '关注', 
      label: '关注'
    }
  ];

  // 处理菜谱点击事件 - 修复：传递完整的菜谱数据
  const handleRecipeClick = (recipe: Recipe) => {
    console.log('点击菜谱:', recipe); // 调试日志
    if (onRecipeClick) {
      onRecipeClick(recipe.id);
    } else {
      // 关键修复：传递完整的菜谱对象
      navigate(`/recipe/${recipe.id}`, { state: { recipe } });
    }
  };

  // 根据当前标签获取对应的食谱数据
  const getCurrentRecipes = () => {
    switch (activeTab) {
      case '发现':
        return discoverRecipes;
      case '关注':
        return followRecipes;
      default:
        return discoverRecipes;
    }
  };

  const currentRecipes = getCurrentRecipes();
  const featuredRecipe = currentRecipes[0];
  const smallRecipes = currentRecipes.slice(1, 5);

  // 格式化烹饪时间（毫秒转换为分钟）
  const formatDuration = (duration: number) => {
    const minutes = Math.ceil(duration / 60000);
    return `${minutes}分钟`;
  };

  // 格式化难度等级
  const formatDifficulty = (difficulty: number) => {
    const levels = ['简单', '初级', '中等', '困难', '专家'];
    return levels[difficulty - 1] || '未知';
  };

  // 获取难度颜色
  const getDifficultyColor = (difficulty: number) => {
    const colors = ['#52c41a', '#1890ff', '#faad14', '#fa541c', '#f5222d'];
    return colors[difficulty - 1] || '#d9d9d9';
  };

  // 处理图片URL
  const processImageUrl = (imagePath: string): string => {
    if (!imagePath) return '';
    if (imagePath.startsWith('http')) return imagePath;
    if (imagePath.startsWith('/')) {
      const baseUrl = getApiBaseUrl().replace('/api', '');
      return `${baseUrl}${imagePath}`;
    }
    const baseUrl = getApiBaseUrl().replace('/api', '');
    return `${baseUrl}/${imagePath}`;
  };

  // 大图卡片组件 - 固定信息位置
  const LargeRecipeCard = ({ recipe }: { recipe: Recipe }) => (
    <div
      style={{
        position: 'relative',
        width: '100%',
        maxWidth: '420px',
        height: '600px',
        margin: '0 auto',
        cursor: 'pointer',
        borderRadius: '16px',
        overflow: 'hidden',
        boxShadow: '0 8px 32px rgba(0,0,0,0.1)',
      }}
      // 修复：传递完整的菜谱对象
      onClick={() => handleRecipeClick(recipe)}
      onMouseEnter={(e) => {
        const img = e.currentTarget.querySelector('img');
        if (img) img.style.transform = 'scale(1.05)';
      }}
      onMouseLeave={(e) => {
        const img = e.currentTarget.querySelector('img');
        if (img) img.style.transform = 'scale(1)';
      }}
    >
      {/* 图片容器 - 确保完全覆盖 */}
      <div style={{
        position: 'absolute',
        top: 0,
        left: 0,
        width: '100%',
        height: '100%',
        overflow: 'hidden'
      }}>
        <img
          alt={recipe.title}
          src={processImageUrl(recipe.coverImage)}
          style={{
            width: '100%',
            height: '100%',
            objectFit: 'cover',
            objectPosition: 'center',
            transition: 'transform 0.3s ease'
          }}
          onError={(e) => {
            e.currentTarget.src = 'https://images.unsplash.com/photo-1559847844-5315695d62e4?w=420&h=600&fit=crop';
          }}
        />
      </div>
      
      {/* 固定位置的信息叠加层 - 始终在右下角 */}
      <div style={{
        position: 'absolute',
        bottom: 0,
        left: 0,
        right: 0,
        background: 'linear-gradient(transparent, rgba(0,0,0,0.9))',
        color: 'white',
        padding: '20px',
        minHeight: '120px', // 固定高度确保信息区域一致
        display: 'flex',
        flexDirection: 'column',
        justifyContent: 'flex-end'
      }}>
        <Text style={{ 
          color: 'white', 
          fontSize: '20px', 
          fontWeight: 'bold', 
          display: 'block',
          marginBottom: '8px',
          lineHeight: 1.2,
          textShadow: '0 2px 4px rgba(0,0,0,0.8)'
        }}>
          {recipe.title}
        </Text>
        
        {/* 食谱信息行 */}
        <div style={{ 
          display: 'flex', 
          justifyContent: 'space-between',
          alignItems: 'center',
          flexWrap: 'wrap',
          gap: '8px'
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
            {/* 难度标签 */}
            <div style={{
              background: getDifficultyColor(recipe.difficulty),
              color: 'white',
              padding: '4px 8px',
              borderRadius: '12px',
              fontSize: '12px',
              fontWeight: 'bold',
              whiteSpace: 'nowrap'
            }}>
              {formatDifficulty(recipe.difficulty)}
            </div>
            
            {/* 时间 */}
            <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
              <ClockCircleOutlined style={{ fontSize: '12px', opacity: 0.9 }} />
              <Text style={{ color: 'white', fontSize: '12px', opacity: 0.9, whiteSpace: 'nowrap' }}>
                {formatDuration(recipe.duration)}
              </Text>
            </div>
          </div>
          
          {/* 点赞数 */}
          <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
            <HeartOutlined style={{ fontSize: '14px', color: '#ff4d4f' }} />
            <Text style={{ color: 'white', fontSize: '14px', fontWeight: 'bold', whiteSpace: 'nowrap' }}>
              {recipe.likesCount}
            </Text>
          </div>
        </div>
      </div>
    </div>
  );

  // 小图卡片组件 - 固定信息位置
  const SmallRecipeCard = ({ recipe }: { recipe: Recipe }) => (
    <div
      style={{
        position: 'relative',
        width: '100%',
        maxWidth: '190px',
        height: '270px',
        margin: '0 auto',
        cursor: 'pointer',
        borderRadius: '12px',
        overflow: 'hidden',
        boxShadow: '0 4px 16px rgba(0,0,0,0.1)',
      }}
      // 修复：传递完整的菜谱对象
      onClick={() => handleRecipeClick(recipe)}
      onMouseEnter={(e) => {
        const img = e.currentTarget.querySelector('img');
        if (img) img.style.transform = 'scale(1.08)';
      }}
      onMouseLeave={(e) => {
        const img = e.currentTarget.querySelector('img');
        if (img) img.style.transform = 'scale(1)';
      }}
    >
      {/* 图片容器 - 确保完全覆盖 */}
      <div style={{
        position: 'absolute',
        top: 0,
        left: 0,
        width: '100%',
        height: '100%',
        overflow: 'hidden'
      }}>
        <img
          alt={recipe.title}
          src={processImageUrl(recipe.coverImage)}
          style={{
            width: '100%',
            height: '100%',
            objectFit: 'cover',
            objectPosition: 'center',
            transition: 'transform 0.3s ease'
          }}
          onError={(e) => {
            e.currentTarget.src = 'https://images.unsplash.com/photo-1559847844-5315695d62e4?w=190&h=270&fit=crop';
          }}
        />
      </div>
      
      {/* 固定位置的信息叠加层 - 始终在右下角 */}
      <div style={{
        position: 'absolute',
        bottom: 0,
        left: 0,
        right: 0,
        background: 'linear-gradient(transparent, rgba(0,0,0,0.9))',
        color: 'white',
        padding: '12px',
        minHeight: '60px', // 固定高度确保信息区域一致
        display: 'flex',
        flexDirection: 'column',
        justifyContent: 'flex-end'
      }}>
        <Text style={{ 
          color: 'white', 
          fontSize: '14px', 
          fontWeight: 'bold', 
          display: 'block',
          marginBottom: '4px',
          lineHeight: 1.2,
          textShadow: '0 1px 2px rgba(0,0,0,0.8)',
          whiteSpace: 'nowrap',
          overflow: 'hidden',
          textOverflow: 'ellipsis'
        }}>
          {recipe.title}
        </Text>
        
        <div style={{ 
          display: 'flex', 
          justifyContent: 'space-between',
          alignItems: 'center'
        }}>
          <div style={{
            background: getDifficultyColor(recipe.difficulty),
            color: 'white',
            padding: '2px 6px',
            borderRadius: '8px',
            fontSize: '10px',
            fontWeight: 'bold',
            whiteSpace: 'nowrap'
          }}>
            {formatDifficulty(recipe.difficulty)}
          </div>
          
          <div style={{ display: 'flex', alignItems: 'center', gap: '2px' }}>
            <HeartOutlined style={{ fontSize: '10px', color: '#ff4d4f' }} />
            <Text style={{ color: 'white', fontSize: '10px', fontWeight: 'bold', whiteSpace: 'nowrap' }}>
              {recipe.likesCount}
            </Text>
          </div>
        </div>
      </div>
    </div>
  );

  // 错误显示组件
  const ErrorDisplay = () => (
    <div style={{ 
      textAlign: 'center', 
      padding: '80px 20px',
      background: 'rgba(255, 253, 248, 0.9)',
      borderRadius: '16px',
      border: `1px solid ${colorConfig.border}`,
      margin: '20px',
      boxShadow: '0 4px 16px rgba(0,0,0,0.05)'
    }}>
      <ExclamationCircleOutlined style={{ fontSize: '56px', color: '#ff4d4f', marginBottom: '20px' }} />
      <h3 style={{ color: colorConfig.primaryDark, marginBottom: '12px', fontSize: '18px' }}>数据加载失败</h3>
      <p style={{ color: colorConfig.primaryDark, marginBottom: '20px', opacity: 0.7, fontSize: '14px' }}>
        {apiError}
      </p>
      <div style={{ marginBottom: '20px', fontSize: '13px', color: colorConfig.primaryDark, opacity: 0.6 }}>
        <div>请检查：</div>
        <div>1. 网络连接是否正常</div>
        <div>2. 认证token是否有效</div>
        <div>3. API服务是否可用</div>
      </div>
      <Button 
        type="primary" 
        icon={<ReloadOutlined />} 
        onClick={reloadData}
        size="large"
        style={{
          backgroundColor: colorConfig.primary,
          borderColor: colorConfig.primary,
          color: colorConfig.primaryDark,
          fontWeight: 'bold',
          borderRadius: '20px',
          padding: '0 24px',
          height: '40px'
        }}
      >
        重新加载
      </Button>
    </div>
  );

  if (loading && currentRecipes.length === 0) {
    return (
      <Layout style={{ 
        minHeight: '100vh', 
        backgroundImage: "url('/background2.jpg')",
        backgroundSize: 'cover',
        backgroundPosition: 'center',
      }}>
        <Sidebar />
        <Layout style={{ background: 'transparent' }}>
          <Content style={{ 
            display: 'flex', 
            justifyContent: 'center', 
            alignItems: 'center',
            margin: '0 40px 20px 40px',
          }}>
            <Spin size="large" tip="加载中..." style={{ color: colorConfig.primary }} />
          </Content>
        </Layout>
      </Layout>
    );
  }

  return (
    <Layout style={{ 
      minHeight: '100vh', 
      backgroundImage: "url('/background2.jpg')",
      backgroundSize: 'cover',
      backgroundPosition: 'center',
    }}>
      <Sidebar />
      
      <Layout style={{ background: 'transparent' }}>
        {/* 头部 - 与Message界面相同的样式 */}
        <Header style={{
          background: 'white',
          boxShadow: '0 2px 8px rgba(0,0,0,0.05)',
          padding: '0 40px',
          height: 'auto',
          lineHeight: '64px',
          borderRadius: '12px 12px 0 0',
          margin: '20px 40px 0 40px',
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center'
        }}>
          <h2 style={{ margin: 0, fontSize: '24px', fontWeight: 'bold', color: colorConfig.primaryDark }}>
            美食社区
          </h2>
          <div style={{ display: 'flex', gap: '12px' }}>
            <Button 
              type="default"
              style={{
                borderRadius: '20px',
                fontWeight: 'bold',
                borderColor: colorConfig.border,
                color: colorConfig.primaryDark
              }}
              onClick={reloadData}
              disabled={loading}
            >
              {loading ? '加载中...' : '刷新数据'}
            </Button>
          </div>
        </Header>

        <Content style={{ 
          margin: '0 40px 20px 40px',
          padding: '0',
          background: 'transparent',
        }}>
          <div style={{
            background: 'white',
            padding: '24px',
            borderRadius: '0 0 12px 12px',
            minHeight: 'calc(100vh - 200px)'
          }}>
            {/* 标签栏 - 使用与Message界面相同的card样式 */}
            <Tabs
              activeKey={activeTab}
              onChange={setActiveTab}
              type="card"
              items={tabItems.map(item => ({
                ...item,
                label: (
                  <span style={{ color: colorConfig.primaryDark }}>
                    {item.label}
                  </span>
                )
              }))}
              style={{
                ['--antd-tab-active-color' as any]: colorConfig.primaryDark,
                ['--antd-tab-ink-bar-color' as any]: colorConfig.primary,
              }}
            />

            {/* 错误显示 */}
            {apiError && <ErrorDisplay />}

            {/* 食谱网格布局 */}
            {!apiError && currentRecipes.length > 0 ? (
              <div style={{ padding: '24px 0' }}>
                <Row gutter={[32, 32]} justify="center" align="middle">
                  {/* 左侧大图 */}
                  <Col xs={24} lg={10}>
                    {featuredRecipe && <LargeRecipeCard recipe={featuredRecipe} />}
                  </Col>

                  {/* 右侧四张小图 - 2x2田字排列 */}
                  <Col xs={24} lg={14}>
                    <Row gutter={[16, 16]} justify="center">
                      {smallRecipes.map((recipe) => (
                        <Col key={recipe.id} xs={12} style={{ display: 'flex', justifyContent: 'center' }}>
                          <SmallRecipeCard recipe={recipe} />
                        </Col>
                      ))}
                    </Row>
                  </Col>
                </Row>
              </div>
            ) : !apiError ? (
              <div style={{ 
                textAlign: 'center', 
                padding: '80px 0',
                color: colorConfig.primaryDark,
                opacity: 0.5,
                fontSize: '16px'
              }}>
                暂无食谱数据
              </div>
            ) : null}
          </div>
        </Content>
      </Layout>
    </Layout>
  );
};

export default RecipeCommunity;